<?php

class HomeController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',
				'actions'=>array('index','view', 'loadmetros', 'yandex', 'phone'),
				'users'=>array('*'),
			),
			array('allow',
				'actions'=>array('create'),
				'roles'=>array('save_home'),
			),
			array('allow',
				'actions'=>array('update'),
				'roles'=>array('update_home'),
			),
			array('allow',
				'actions'=>array('admin','delete'),
				'roles'=>array('delete_home'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$showPhone = true;
		
		// проверяем по базе оплат, можно ли пользователю смотреть телефоны хозяев

		$criteria = new CDbCriteria;
		$criteria->condition = 'id != :id AND status = :status';
		$criteria->params=array(':id'=>$id, ':status'=>1);
		$criteria->limit = 4;
		$criteria->order = 'rand()';
		
		// похожие объявления
		$other = Home::model()->findAll($criteria);
		
		Yii::app()->getClientScript()->registerCssFile(Yii::app()->baseUrl.'/css/gallery.css');
		Yii::app()->getClientScript()->registerScriptFile("http://api-maps.yandex.ru/2.1/?lang=ru_RU");
		
		
		Yii::app()->getClientScript()->registerCssFile(Yii::app()->baseUrl.'/css/jcarous.css');
		
		Yii::app()->getClientScript()->registerCssFile(Yii::app()->baseUrl.'/css/layout.css');
		Yii::app()->getClientScript()->registerCssFile(Yii::app()->baseUrl.'/css/style1.css');
		
		//Yii::app()->getClientScript()->registerCssFile("/js/fancy/jquery.fancybox.css?v=2.1.5");
		//Yii::app()->getClientScript()->registerScriptFile("/js/fancy/jquery.fancybox.js?v=2.1.5");
		
		$model = $this->loadModel($id);
		
		$this->_h1 = $model->getH1();
		$this->_title = $model->title;
		
		$section = $model->getParentSection();
		
		$this->breadcrumbs = array(
			'Аренда' => $this->createUrl('home/index',array('city'=>'nsk')),
			$section['caption'] => $section['url'],
			$model->getAddress()
		);
		
		$this->render('view_new',array(
			'model'=>$model,
			'showPhone'=>$showPhone,
			'other' => $other,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Home;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Home']))
		{
			$model->attributes=$_POST['Home'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Home']))
		{
			$model->attributes=$_POST['Home'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$showPhone = true;
		
		$city_id = 1;//Yii::app()->request->getParam('city')
		
		$homes = new Home;
		$homes->attributes = Yii::app()->request->getParam('Home', array('city_id'=>$city_id)); 
		
		$pages;
		
		$dataProvider = $homes->search($pages);
		$filter = Home::getFilter();
		
		Yii::app()->getClientScript()->registerScriptFile("http://api-maps.yandex.ru/2.0-stable/?load=package.standard&lang=ru_RU");
		
		$this->render('index',array(
			'dataProvider' => $dataProvider,
			'filter' => $filter,
			'showPhone'=>$showPhone,
			'pages' => $pages,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Home('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Home']))
			$model->attributes=$_GET['Home'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Home the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Home::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Home $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='home-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function actionLoadmetros()
	{
		/*$data = Metro::model()->findAll('city_id=:city_id',
				array(':city_id'=>(int) $_POST['city_id']));
	
		$data = CHtml::listData($data,'id','caption');
	
		echo "<option value=''>Выберите метро</option>";
		foreach ($data as $value=>$city_name)
			echo CHtml::tag('option', array('value'=>$value),CHtml::encode($city_name),true);
		*/
		$model = new Home;
		
		$city_id = Yii::app()->request->getParam('city_id');		
		// метро города
		$metro = Home::model()->getMetros($city_id);
		
		// районы города
		$district = Home::model()->getDiscricts($city_id);
		
		$this->renderPartial('_district',array(
			'district' => $district,
			'metro' => $metro,
			'model' => $model,
		));
	}
	
	public function actionYandex() {
		$home_id = Yii::app()->request->getParam('id', 0);
		
		if (!$home_id) return;
		
		$model = Home::model()->findByPk($home_id);
		
		$this->renderPartial('yandex_map', array(
			'model' => $model,
		));
	}
	
	public function actionPhone () {
		$id = Yii::app()->request->getParam('id', 0);
		if (false && !$id) {
			echo '<span>Нет доступа</span>';
			return;
		}
		
		$model = Home::model()->findByPk($id);
		echo '<span>'.CHtml::image($model->getPhone()).'</span>';
	}
}
